import React from 'react';
import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';
import {createRoot} from 'react-dom/client';
import {Box} from "@mui/material";

const Login = ({message}) => (
    <Box sx={{display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 4}}>
        <span>{message}</span>
        <a style={{textDecoration: 'none'}} href="/login">登录</a>
    </Box>
);

export function alert(message, severity = 'success', duration = 5000, login = false) {

    const div = document.createElement('div');
    document.body.appendChild(div);
    const root = createRoot(div);

    if (login) {
        document.querySelectorAll('body > *').forEach(
            e => e.classList.add('modal-overlay')
        );
    }

    const handleClose = (_, reason) => {
        if (reason !== 'clickaway') {
            root.unmount();
            document.body.removeChild(div);
            if (login) {
                window.location.href = '/login';
            }
        }
    };

    root.render(
        <Snackbar sx={{zIndex: 9999}} open
                  anchorOrigin={{vertical: 'top', horizontal: 'center'}}
                  autoHideDuration={duration}
                  onClose={handleClose}>
            <Alert severity={severity}>{login ? <Login message={message}/> : message}</Alert>
        </Snackbar>
    );
}

export function alertLogin() {
    return alert('你还没有登录，或登录已过期', 'error', 5000, true);
}
